<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="45%"
        v-model="modleVisible"
        :title="form.id ? '编辑区划' : '新增区划'"
        @cancel="() => (this.modleVisible = false)"
        :confirm-loading="formButtonDisableFlag"
        @ok="onSubmit"
      >
        <div id="modalContent">
          <div class="formAspin" v-if="editWaitForLoading">
            <a-spin />
          </div>
          <div class="modalContentForm">
            <a-form-model
              ref="formRef"
              :model="form"
              :rules="rules"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-row type="flex" justify="space-between">
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="区划名称"
                    prop="name"
                    placeholder="请输入区划名称"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="区划代码"
                    prop="code"
                    placeholder="请输入区划代码"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="上级区域代码"
                    prop="parentCode"
                    disabled
                    placeholder="根据区划代码自动生成"
                  ></Input>
                </a-col>
                <a-col :span="12">
                  <Input
                    :form="form"
                    label="区域级别"
                    prop="areaLevel"
                    disabled
                    placeholder="根据区划代码自动生成"
                  ></Input>
                </a-col>
                <!-- <a-col :span="12">
                  <Select
                    :form="form"
                    label="状态"
                    prop="isEnable"
                    placeholder="请选择状态"
                    :optList="getIsEnableOption()"
                  ></Select>
                </a-col> -->
              </a-row>
            </a-form-model>
          </div>
        </div>
      </a-modal>
      <typicalSearch ref="insideSearch" :searchConfig="searchConfig" @searchMethod="getTableData"></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">区划管理</div>
          <div class="addButton">
            <a-button type="primary" @click="handleEdit()">
              新增区划
            </a-button>
          </div>
        </div>
        <div class="tableList">
          <typicalTable ref="insideTable" :tableConfig="tableConfig" :tableData="tableData" @getTableData="getTableData">
            <template v-slot="slotProps">
              <Button label="编辑" @click="handleEdit(slotProps.record)"></Button>
              <a-popconfirm
                slot="action"
                title="此操作将删除该条数据，是否继续?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(slotProps.record)"
              >
                <Button type="stop" label="删除"></Button>
              </a-popconfirm>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import {
  listAreas,
  createArea,
  updateArea,
  loadAreaById,
  deleteAreaById
} from '@/api/api';
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import Select from '@/components/typicalControl/select';
import Button from '@/components/typicalControl/button';
import { getIsEnableOption } from '@/utils/frequentInterface';
export default {
  name: 'JurisdictionManage',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Button: Button,
    Select: Select,
    Input: Input
  },
  data() {
    var validateCode = (rule, value, callback) => {
      // const sixNum = /^[0-9]\d{5}$/;
      const sixNum = /^(0|[0-9]\d{0,6})?$/;
      if (!value && value !== 0) {
        callback(new Error('请输入区划代码'));
      } else if (value.length > 6 || value.length % 2 !== 0 || !sixNum.test(value)) {
        callback(new Error('区划代码不符合规范'));
      } else {
        // 通过校验自动生成数据
        this.automaticCode();
        callback();
      }
    };
    return {
      formButtonDisableFlag: false, // 表单确定禁用按钮 防止多次点击多次保存
      editWaitForLoading: false, // 加载编辑回显数据等待Loading
      roleLoading: false, // 加载表格的loading
      modleVisible: false, // 控制弹框
      form: {
        name: undefined,
        code: undefined,
        isEnable: 1,
        isSystem: 0,
        parentCode: undefined,
        areaLevel: undefined
      },
      rules: {
        // 规则验证
        name: [
          { required: true, message: '请输入区划名称', trigger: 'blur' },
          { max: 15, message: '最大长度不能超过15个字', trigger: 'blur' }
        ],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }]
      },
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchName',
            value: '',
            label: '区划名称'
          },
          {
            type: 'input',
            prop: 'searchCode',
            value: '',
            label: '区划代码'
          },
          {
            type: 'input',
            prop: 'searchAreaLevel',
            value: '',
            label: '区域级别'
          }
        ],
        parent: this
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '区划名称',
            dataIndex: 'name',
            ellipsis: true
          },
          {
            title: '区划代码',
            dataIndex: 'code',
            ellipsis: true
          },
          {
            title: '区域级别',
            dataIndex: 'areaLevel',
            ellipsis: true
          },
          // {
          //   title: '状态',
          //   dataIndex: 'isEnable',
          //   scopedSlots: { customRender: 'isEnable' },
          //   width: '80px'
          // },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            ellipsis: true,
            customRender: this.formatterTime
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true
          }
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this
      },
      // 列表组件数据
      tableData: {
        content: [],
        totalElements: 0
      }
    };
  },
  created() {
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getIsEnableOption,
    /**
     * [automaticCode 根据code自动上级code,级别]
     * @return {[type]} [description]
     */
    automaticCode() {
      const le = this.form.code.length;
      this.form.areaLevel = le / 2;
      if (this.form.areaLevel === 1) {
        this.form.parentCode = 0;
      } else {
        this.form.parentCode = this.form.code.substr(0, le - 2);
      }
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      this.roleLoading = true;
      listAreas(searchParam).then(res => {
        if (res.code == 200 && res.data.content) {
          this.tableData = res.data;
        } else {
          this.tableData.content = [];
          this.tableData.totalElements = 0;
        }
      }).finally(() => {
        this.roleLoading = false;
      });
    },
    /**
     * @description: 新增编辑区划表单提交
     */
    onSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.formButtonDisableFlag = true;
          if (this.form.id) {
            this.editRole(this.form);
          } else {
            this.roleAdd(this.form);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        name: undefined,
        code: undefined,
        isEnable: 1,
        isSystem: 0,
        parentCode: undefined,
        areaLevel: undefined
      };
    },

    /**
     * @description: 新增区划权限
     * @param {object} addRoleParam 表单参数
     */
    roleAdd(addRoleParam) {
      createArea({ body: addRoleParam })
        .then(res => {
          this.formSuccessOperation(res);
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 编辑区划权限
     * @param {object} editRoleParam 表单参数
     */
    editRole(editRoleParam) {
      updateArea({ body: editRoleParam, id: editRoleParam.id })
        .then(res => {
          this.formSuccessOperation(res);
        })
        .finally(() => {
          this.formButtonDisableFlag = false;
        });
    },

    /**
     * @description: 表单新增编辑成功后的公共的代码 （消息提示 搜索框重置 请求表格数据）
     * @param {object} successFormData 表单请求成功后返回的对象
     */
    formSuccessOperation(successFormData) {
      this.$message.success(successFormData.message);
      this.modleVisible = false;
      this.$refs.insideTable.updateListData();
    },

    /**
     * [handleEdit 新增或编辑]
     * @param  {[type]} row [如果编辑入参行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.modleVisible = true;
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.form = this.initializationForm();
      if (row) {
        this.editWaitForLoading = true;
        loadAreaById({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              this.form = Object.assign(this.form, res.data);
            }
          })
          .finally(() => {
            this.editWaitForLoading = false;
          });
      }
    },

    /**
     * @description: 点击删除
     * @param {object} roleTableRowData 格某一行的数据对象
     */
    handleDelete(roleTableRowData) {
      deleteAreaById({ id: roleTableRowData.id }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.$refs.insideTable.updateListData();
        }
      });
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    }
  }
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 200px;
  position: relative;
  .formAspin {
    position: absolute;
    width: 100%;
    height: 200px;
    background: #ececec;
    border-radius: 4px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
